package net.xxcxcxcx.xc_enhancedmob.mixin;

import net.minecraft.entity.Entity;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.network.Packet;
import net.minecraft.server.network.EntityTrackerEntry;
import net.xxcxcxcx.xc_enhancedmob.component.BaseComponent;
import net.xxcxcxcx.xc_enhancedmob.component.EnhancedBaseComponent;
import net.xxcxcxcx.xc_enhancedmob.data.MobData;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import java.util.function.Consumer;

@Mixin(EntityTrackerEntry.class)
public abstract class UpdateMoreTitleMixin {
    @Shadow
    @Final
    private Entity entity;

    //发送更新文本的数据包
    @Inject(method = "sendPackets", at = @At(value = "RETURN"))
    public void sendPacketsall(Consumer<Packet<?>> sender, CallbackInfo ci) {
        if (entity instanceof MobEntity mobEntity) {
            BaseComponent baseComponent = ((MobData) mobEntity).getComponent(EnhancedBaseComponent.class.getName());
            if (baseComponent instanceof EnhancedBaseComponent enhancedBaseComponent) {
                enhancedBaseComponent.Update();
                enhancedBaseComponent.setDirtytitle(true);
            }
        }
    }

    @Inject(method = "syncEntityData", at = @At(value = "RETURN"))
    public void sendPackets(CallbackInfo ci) {
        if (entity instanceof MobEntity mobEntity) {
            BaseComponent baseComponent = ((MobData) mobEntity).getComponent(EnhancedBaseComponent.class.getName());
            if (baseComponent instanceof EnhancedBaseComponent enhancedBaseComponent && enhancedBaseComponent.getDirtytitle()) {
                enhancedBaseComponent.Update();
                enhancedBaseComponent.setDirtytitle(false);
            }
        }
    }
}
